package com.rongzhe.house.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.exception.RongZheBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Created by JackWangon[www.coder520.com] 2017/11/16.
 */
@Service("verCodeService")
@Slf4j
public class AliyunSMSService implements SmsSender{


    @Override
    public void sendSms(String phone, String tplId, String params) {
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "6000");
            System.setProperty("sun.net.client.defaultReadTimeout", "6000");
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Constants.ALSMS_ACCESS_KEY,
                    Constants.ALSMS_ACCESS_SECRET);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", Constants.ALSMS_MS_PRODUCT, Constants.ALSMS_DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            request.setPhoneNumbers(phone);
            request.setSignName(Constants.ALSMS_SIGNNAME);
            request.setTemplateCode(tplId);
            request.setTemplateParam("{\"code\":\""+params+"\"}");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) {
                log.error("fail to send vercode",new RongZheBusinessException("短信验证码发送失败"));
            }

        } catch (ClientException e) {
            log.error("fail to send vercode",e);
        }


    }
}
